package com.futvan.z.erp.crm_customer_ticket;

import com.futvan.z.erp.customer.CustomerService;
import com.futvan.z.erp.customer.crm_customer;
import com.futvan.z.erp.customer.crm_customer_address;
import com.futvan.z.erp.customer_notice.Customer_noticeService;
import com.futvan.z.erp.erp_account.erp_account;
import com.futvan.z.erp.zproduct.ZproductService;
import com.futvan.z.erp.zproduct.z_product;
import com.futvan.z.erp.zstorehouse.ZstorehouseService;
import com.futvan.z.erp.zstorehouse.z_storehouse;
import com.futvan.z.erp.zstorehouse.z_storehouse_area;
import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.*;
import com.futvan.z.shop.order.OrderService;
import com.futvan.z.shop.order.s_order;
import com.futvan.z.shop.order.s_order_products;
import com.futvan.z.shop.sticket.SticketService;
import com.futvan.z.shop.sticket.s_ticket;
import com.futvan.z.shop.sticket.s_ticket_product;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

@Controller
public class Crm_customer_ticketTicketGrantButtonAction extends SuperAction {
    @Resource
    private CustomerService customerService;
    @Resource
    private Crm_customer_ticketService crm_customer_ticketService;
    @Resource
    private SticketService sticketService;
    @Resource
    private ZproductService zproductService;
    @Resource
    private OrderService orderService;
    @Resource
    private ZstorehouseService zstorehouseService;
    @Resource
    private Customer_noticeService customer_noticeService;


    @RequestMapping(value = "/openUploadTicket")
    public ModelAndView openUploadTicket(@RequestParam HashMap<String, String> bean) throws Exception {
        //从Session中获取用户与组织信息保存到Bean中
        GetSessionInfoToBean(bean, request);
        ModelAndView model = new ModelAndView("erp/customer/ticketUpload");
        model.addObject("bean", bean);
        return model;
    }

    @CrossOrigin(origins = "*", maxAge = 360000)
    @RequestMapping(value = "/resolve")
    public @ResponseBody
    Result resolveTicket(String filepath, HttpServletRequest request) {
        Result result = new Result();
        String fileReturnPath = "";
        try {
            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        //创建保存路径
                        String rootDirectory = request.getServletContext().getRealPath("/") + "files";
                        // 判断文件目录是否存在如果不存在怎么创建
                        File dir = new File(rootDirectory);
                        if (!dir.exists() && !dir.isDirectory()) {
                            //创建多级目录
                            dir.mkdirs();
                        }
                        //保存文件
                        String filename = StringUtil.UrlDecode(file.getOriginalFilename());
                        save(file, rootDirectory + "/" + filename);
                        //创建返回URL
//                        String httpHead = "http://";
//                        if ("true".equals(z.sp.get("isSSL"))) {
//                            httpHead = "https://";
//                        }
//                        fileReturnPath = httpHead + "testshopservice.jlsmerro.com:8888" + "/files/" + filename;
                        fileReturnPath = rootDirectory + "/" + filename;

                        return faFang(fileReturnPath);
                    }
                }

                if (z.isNotNull(fileReturnPath)) {
                    result.setSuccess(fileReturnPath);
                } else {
                    result.setError("未上传文件");
                }
            } else {
                result.setError("没有获取到上传文件");
            }

        } catch (Exception e) {
            result.setCode(Code.ERROR);
            result.setMsg("file upload error：" + e.getMessage());
            result.setData(e.getMessage());
        }
        return result;

//        String url = bean.get("url");
//        String paths = System.getProperty(z.sp.get("tempfiles")) + "/temp/importExcel";
        //下载到本地 /Users/a77/IdeaProjects/shop_admin
//        String path = HttpUtil.download(url, "/Users/a77/IdeaProjects/shop_admin" + "/temp/importExcel", "ticketExcel");
//        //解析excel
//        List<excel_ticket> ticketExcel = TicketExcelUtil.parseFromExcel(path, 1, excel_ticket.class);

    }


    public Result faFang(String path) throws Exception {
//        String path = bean.get("url");
        Result result = new Result();
        List<excel_ticket> ticketExcel = TicketExcelUtil.parseFromExcel(path, 1, excel_ticket.class);
        if (z.isNotNull(ticketExcel)) {
            //过滤空数据
            List<excel_ticket> list = ticketExcel.stream().filter(ticket -> ticket.getCustomid() != null && !"".equals(ticket.getCustomid())).collect(Collectors.toList());

            //验证信息有效性
            Result checkResult = checkInfo(list);
            if (checkResult.ifError()) {
                return checkResult;
            }

            try {
                for (excel_ticket t : list) {
                    //生成礼券
                    for (int i = 0; i < t.getCount(); i++) {
                        Result create_customer_ticket_result = ticketInsert(t);
                        if (create_customer_ticket_result.ifSuccess()) {
                            crm_customer_ticket customerTicket = (crm_customer_ticket) create_customer_ticket_result.getData();
                            Result create_notice_result = noticeInsert(t, customerTicket);
                            if (create_notice_result.ifError()) {
                                z.Exception("通知生成失败");
                            }
                        } else {
                            z.Exception("生成礼券失败");
                        }
                    }

                    if ("是".equals(t.getDirect_delivery())) {
                        //生成订单
                        Result create_order_result = setOrder(t);
                        if (create_order_result.ifError()) {
                            z.Exception("订单生成失败");
                        }
                    }
                    result.setSuccess();
                }
            } catch (Exception e) {
                z.Exception("发放失败");
            }
        } else {
            result.setError("文件解析失败，请重新上传");
        }
        return result;
    }


    @RequestMapping(value = "/getInfo")
    public @ResponseBody
    Result resolveTicket(@RequestParam HashMap<String, String> bean) throws Exception {
        String path = bean.get("url");
        Result result = new Result();
        String rootDirectory = request.getServletContext().getRealPath("/") + "files";
        List<excel_ticket> ticketExcel = TicketExcelUtil.parseFromExcel(path, 1, excel_ticket.class);
        if (z.isNotNull(ticketExcel)) {
            //过滤空数据
            List<excel_ticket> list = ticketExcel.stream().filter(ticket -> ticket.getCustomid() != null).collect(Collectors.toList());

            //验证信息有效性
            Result checkResult = checkInfo(list);
            if (checkResult.ifError()) {
                return checkResult;
            }

            try {
                for (excel_ticket t : list) {
                    //生成礼券
                    Result create_customer_ticket_result = ticketInsert(t);

                    if (create_customer_ticket_result.ifSuccess()) {

                        crm_customer_ticket customerTicket = (crm_customer_ticket) create_customer_ticket_result.getData();

                        if ("1".equals(customerTicket.getIs_use())) {
                            //生成订单
                            Result create_order_result = setOrder(t);

                            if (create_order_result.ifError()) {
                                z.Exception("订单生成失败");
                            }
                        }

                        Result create_notice_result = noticeInsert(t, customerTicket);
                        if (create_notice_result.ifError()) {
                            z.Exception("通知生成失败");
                        }
                        result.setSuccess();
                    } else {
                        z.Exception("生成礼券失败");
                    }
                }
            } catch (Exception e) {
                z.Exception("发放失败");
            }
        } else {
            result.setError("文件解析失败，请重新上传");
        }
        return result;
    }


    /**
     * 保存文件
     *
     * @throws Exception
     */
    private void save(MultipartFile file, String fileSavePath) throws Exception {
        file.transferTo(new File(fileSavePath));
    }

    /**
     * 验证信息
     *
     * @param list
     * @return
     * @throws Exception
     */
    public Result checkInfo(List<excel_ticket> list) throws Exception {
        Result result = new Result();
        boolean canSend = false;
        //验证信息有效性
        if (z.isNotNull(list)) {
            for (int i = 0; i < list.size(); i++) {
                StringBuffer stringBuffer = new StringBuffer();
                //验证客户有效性
                crm_customer customerInfo = customerService.getCustomerInfo(list.get(i).getCustomid());
                if (z.isNull(customerInfo)) {
                    canSend = true;
                    stringBuffer.append("用户不存在");
                }
                //验证赠品券有效性
                s_ticket ticketInfo = sticketService.getTicketInfo(list.get(i).getTicket());
                if (z.isNull(ticketInfo)) {
                    canSend = true;
                    stringBuffer.append("赠品券不存在");
                }
                list.get(i).setErrorMsg(stringBuffer.toString());
            }
        } else {
            result.setError("列表为空");
        }

        //判断错误列表是否有数据，有则返回
        if (canSend) {

            //创建保存路径
            String rootDirectory = request.getServletContext().getRealPath("/") + "files";
            // 判断文件目录是否存在如果不存在怎么创建
            File dir = new File(rootDirectory);
            if (!dir.exists() && !dir.isDirectory()) {
                //创建多级目录
                dir.mkdirs();
            }

            String date = String.valueOf(System.currentTimeMillis());

            //将错误数据生成excel
            String errorPath = TicketExcelUtil.writeExcelWithTitle(list, rootDirectory + "/" + date + "-errorticket.xls");

            //创建返回URL
            String httpHead = "http://";
            if ("true".equals(z.sp.get("isSSL"))) {
                httpHead = "https://";
            }
            String fileReturnPath = httpHead + z.sp.get("serverip") + "/files/" + date + "-errorticket.xls";


            result.setError("上传失败", fileReturnPath);
            return result;
        }
        result.setSuccess();
        return result;
    }


    /**
     * 插入礼券
     *
     * @param importTicket
     */
    public Result ticketInsert(excel_ticket importTicket) {

        Result result = new Result();

        crm_customer_ticket ticket = new crm_customer_ticket();
        ticket.setCustomid(importTicket.getCustomid());

        if ("是".equals(importTicket.getDirect_delivery().trim())) {
            ticket.setIs_use("1");
            ticket.setCollection_time(DateUtil.getDateTime());
        } else {
            ticket.setIs_use("0");
        }

        List<z_storehouse> storeList = zstorehouseService.getStoreList();
        if (z.isNotNull(storeList) && storeList.size() > 0) {
            for (int j = 0; j < storeList.size(); j++) {
                if (importTicket.getStartStorehouse().equals(storeList.get(j).getName())) {
                    ticket.setStart_storehouse(storeList.get(j).getNumber());//获取仓库id
                }
            }
        } else {
            result.setError("仓库不存在");
        }

        ticket.setTicket(importTicket.getTicket());
        ticket.setAddress(importTicket.getAddress());
        ticket.setRelated_order(importTicket.getRelation_order());
        ticket.setZid(z.newZid());
        ticket.setCreate_time(DateUtil.getDateTime());

        s_ticket ticketInfo = sticketService.getTicketInfo(importTicket.getTicket());
        if (z.isNotNull(ticketInfo)) {
            String term = ticketInfo.getTerm();
            String endtime = DateUtil.DateAdd(null, "yyyy-MM-dd HH:mm:ss", Calendar.DAY_OF_MONTH, Integer.parseInt(term), "yyyy-MM-dd HH:mm:ss");
            ticket.setEndtime(endtime);
        } else {
            result.setError("礼券不存在");
        }

        int i = crm_customer_ticketService.insertTicket(ticket);
        if (i == 1) {
            result.setSuccess();
            result.setData(ticket);
//            noticeInsert(importTicket, ticket);
        } else {
            result.setError("礼券插入失败");
        }
        return result;
    }


    public Result noticeInsert(excel_ticket importTicket, crm_customer_ticket ticket) {
        String title = "";
        String info = "";
        String tips = "";

        if ("是".equals(importTicket.getDirect_delivery())) {
            title = "您的赠品订单已生成，请注意接收";
            info = "<p><span style=\"font-size: 20px;\">您的赠品订单已生成，请留意订单物流信息的更新，接收赠品。</span></p>";
            tips = "0";
        } else {
            title = "您有待领取的赠品，请及时领取";
            info = "<script type=\"text/javascript\">function NowReceive(obj){\n" +
                    "\n" +
                    "var u = navigator.userAgent;\n" +
                    "        if (u.indexOf('Android') >-1 || u.indexOf('Linux') > -1) {//安卓手机\n" +
                    "            android.jsAndroid(obj);\n" +
                    "        } else if (u.indexOf('iPhone') > -1) {//苹果手机\n" +
                    "\t\twindow.webkit.messageHandlers.NowReceive.postMessage(obj);\n" +
                    "           \n" +
                    "        } \n" +
                    "\n" +
                    "        \n" +
                    "}</script>\n" +
                    "<p>\n" +
                    "    <img id=\"NowReceiveId\" alt=\"" + ticket.getZid() + "\" src=\"http://files.jlsmerro.com/files/ljlq.jpg\" width=\"100%\" onclick=\"NowReceive('" + ticket.getZid() + "')\"/>\n" +
                    "</p>";
            tips = "1";

        }
        return customer_noticeService.CreateCustomerNoticeFromTicket(importTicket.getCustomid(), title, info, tips);
    }

    /**
     * 将产品转成订单
     *
     * @throws Exception
     */
    public Result setOrder(excel_ticket ticket) throws Exception {
        Result result = new Result();
        s_order o = new s_order();
        if ("是".equals(ticket.getDirect_delivery().trim())) {
            //获取用户信息
            crm_customer customerInfo = customerService.getCustomerInfo(ticket.getCustomid());
            //判断用户是否存在
            if (z.isNull(customerInfo)) {
                result.setError("用户不存在");
                return result;
            }

            //买家
            o.setBuyer_id(customerInfo.getZid());
            o.setBuyer_name(customerInfo.getNickname());
            o.setBuyer_tel(customerInfo.getTel());
            //开票状态为（未开票）
            o.setInvoicing_status("0");
            //生成订单编号与主键  = 买家小组号+随机数
            String czid = z.newNumber("PS" + customerInfo.getGroup_num(), "yyyyMMdd", 6);
            o.setZid(czid);//主健
            o.setNumber(czid);//编号
            o.setOrder_type("1");//派送订单
            o.setCreate_time(DateUtil.getDateTime());//创建时间
            o.setPay_time(DateUtil.getDateTime());//创建付款时间
            //卖家：如果买家是经销商，默认卖家就是自己
            if ("1".equals(customerInfo.getLevel()) || "经销商".equals(customerInfo.getLevel())) {
                o.setSeller_id(customerInfo.getZid());
                o.setSeller_name(customerInfo.getNickname());
            } else {
                //获取根据买家获取卖家
                crm_customer seller = customerService.getCustomerInfo(customerInfo.getParentid());
                o.setSeller_id(seller.getZid());
                o.setSeller_name(seller.getNickname());
            }
            //小组
            o.setGroup_num(customerInfo.getGroup_num());
            //下单人
            o.setCreate_order_customer(customerInfo.getZid());
            //关联订单
            o.setOther_order_zid(ticket.getRelation_order());
            //状态
            o.setOrder_status("10");
            //默认仓库
            if (z.isNotNull(zstorehouseService.checkStore(ticket.getStartStorehouse()))) {
                o.setStart_storehouse(zstorehouseService.checkStore(ticket.getStartStorehouse()));
            }
            // 验证地址有效性
//            crm_customer_address address = customerService.getAddrewss(list.get(i).getAddress().trim());
//            if (z.isNull(address)) {
//                list.get(i).getAddress().substring(0,2);
//            } else {
//                //默认仓库
//                o.setStart_storehouse(getStartStorehouse(address));
//            }

//            //默认仓库
//            if (z.isNull(customerService.getCustomerDefaultAddress(customerInfo.getZid()))) {
//                o.setStart_storehouse("");
//            } else {
//                o.setStart_storehouse(customerService.getCustomerDefaultAddress(customerInfo.getZid()).getAreaid());
//            }
            //配送公司
            o.setCourier_company(z.sp.get("shop_express_company"));
            o.setCustom_address(ticket.getCustomid());
            //完整地址
            o.setCustom_eaddress_complete(ticket.getAddress());
            //  crm_customer_address cca = customerService.getCustomerDefaultAddress(customerInfo.getZid());
//            cca.setAllinfo(list.get(i).getAddress());
//            //地址
//            if (z.isNotNull(cca)) {
//
//                o.setObj(cca);
//            }
            //客户电话
            o.setCustomer_service_tel(z.sp.get("shop_customer_service_tel"));
            //产品总额
            BigDecimal product_total = new BigDecimal(0);
            //PV总额
            BigDecimal pv_total = new BigDecimal(0);
            Map<String, Object> map = new HashMap<>();
            //产品明细
            List<s_order_products> oplist = new ArrayList<s_order_products>();
            //赠品券信息
            s_ticket ticketInfo = sticketService.getTicketInfo(ticket.getTicket());
            //赠品券关联产品列表
            List<s_ticket_product> ticketProductList = sticketService.getTicketProductList(ticketInfo.getZid());
            for (s_ticket_product stp : ticketProductList) {
                z_product productInfo = zproductService.getProductInfo(stp.getProductid());
                //构建订单产品明细表对象
                s_order_products op = new s_order_products();
                //主键
                op.setZid(z.newZid());
                //外键
                op.setPid(czid);
                //产品ID
                op.setProduct(stp.getProductid());
                //是否赠品
                op.setIs_gift("1");
                //单价
                op.setPrice(productInfo.getPrice_retail());
                op.setPrice("0");
                //金额 = 数量 * 零售价
                //
                BigDecimal count = new BigDecimal(stp.getAmount());
                BigDecimal countlist = new BigDecimal(ticket.getCount());

                BigDecimal multiply = count.multiply(countlist);

                //数量
                op.setAmount(multiply.toString());

                BigDecimal price = new BigDecimal(productInfo.getPrice_retail());
                BigDecimal pv = new BigDecimal(productInfo.getPv());

                BigDecimal total = multiply.multiply(price);
                op.setTotal(total.toString());
                op.setTotal("0");
                //批次+发送U8时获取有效批次信息
                //op.setBatchid(getProductBatchId(p.getZid()));

                //PV总额 = 数量 * PV单价
                BigDecimal pvtotal = multiply.multiply(pv);

                //设置产品对象到obj
                op.setObj(productInfo);
                //总额
                product_total = product_total.add(total);

                //PV总额
                pv_total = pv_total.add(pvtotal);

                //加入订单明细对象
                oplist.add(op);
            }

            map.put("oplist", oplist);
            o.setDetails(map);
            //产品总额
            o.setProduct_total(product_total.toString());
            o.setProduct_total("0");
            //PV总额
            o.setPv_total(pv_total.toString());
            o.setPv_total("0");
            //包邮
            o.setFreight("0");
            //来源
            o.setEquipment_type("pc");
            //合计金额
            o.setTotal(product_total.toString());
            o.setTotal("0");

            //保存订单
            return orderService.insertProduct(o);

        } else {
            result.setSuccess();
        }
        return result;
    }

    /**
     * 根据收货地址，获取发货仓库
     *
     * @return
     */
    public String getStartStorehouse(crm_customer_address address) {
        String default_storehouse_id = "";
        //判读收货ID是否为空
        if (z.isNotNull(address)) {
            //判读收货ID是否有效
            if (z.isNotNull(address)) {
                //获取收货地址对应省份
                String areaid = address.getAreaid().substring(0, 2) + "0000";
                //根据省份找到对应发货仓库ID
                z_storehouse_area sa = zstorehouseService.getStoreArea(areaid);
                if (z.isNotNull(sa)) {
                    default_storehouse_id = sa.getPid();
                } else {
                    default_storehouse_id = getDefaultStoreHouseId();
                }
            } else {
                default_storehouse_id = getDefaultStoreHouseId();
            }
        } else {
            default_storehouse_id = getDefaultStoreHouseId();
        }
        return default_storehouse_id;
    }

    /**
     * 获取默认发货仓库ID
     *
     * @return
     */
    private String getDefaultStoreHouseId() {
        return zstorehouseService.getString();
    }
}